
package com.x52im.rbchat.logic.chat_friend.utils;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.eva.android.ObserverMain;
import com.eva.android.widget.WidgetUtils;
import com.eva.android.widget.WidgetUtils.ToastType;
import com.eva.android.widget.alert.AlertDialog;
import com.x52im.rbchat.MyApplication;
import com.x52im.rbchat.R;
import com.x52im.rainbowchat.http.logic.dto.RosterElementEntity;
import com.x52im.rbchat.logic.chat_friend.gift.GiftsProvider;
import com.x52im.rbchat.logic.chat_friend.gift.model.Gift;
import com.x52im.rbchat.logic.chat_friend.gift.model.GiftInPackageMeta;
import com.x52im.rbchat.logic.chat_friend.gift.model.GiftsMeta;
import com.x52im.rbchat.logic.chat_friend.vv.IRealTimeVoiceWrapper;
import com.x52im.rbchat.logic.chat_friend.vv.RealTimeVoiceWrapper;
import com.x52im.rbchat.logic.chat_friend.vv.VideoActivityNew;
import com.x52im.rbchat.logic.chat_friend.vv.VoiceCallComeDialog;
import com.x52im.rbchat.logic.main.MainActivity;
import com.x52im.rbchat.utils.IntentFactory;

import java.text.MessageFormat;
import java.util.Observable;
import java.util.Observer;

public class ObserverFactory
{
	/**
	 * 视频聊天请求观察者.
	 * <p>
	 * 为何要使用观察者？理由与类{@link VideoActivityNew.BaseEventForVideoChatObserver}相似。
	 */
	public static class ViodeoChatRequestObserver extends ObserverMain
	{
		private final static String TAG = ViodeoChatRequestObserver.class.getSimpleName();
		private Activity activity = null;
		
		public ViodeoChatRequestObserver(Activity activity)
		{
			this.activity = activity;
		}

		public void updateInMain(Observable observable, Object data)
		{
			// 请求发起人的UID
			String A_UID = (String)data;
			RosterElementEntity friendRee = 
					MyApplication.getInstance(activity).getIMClientManager().getFriendsListProvider().getFriendInfoByUid(A_UID);

			System.out.println(">>>>Integer.parseInt(A_UID)="+Integer.parseInt(A_UID));
			
			// 如果正在进行实时语音聊天则不允许开始视频聊天请求
			if(RealTimeVoiceWrapper.isTalkingImpl())
			{
				new AlertDialog.Builder(activity)
				.setTitle(activity.getString(R.string.general_prompt))
				.setMessage(MessageFormat.format(activity.getString(R.string.video_chat_request_at_real_time_chating)
							, (friendRee != null?friendRee.getNickNameWithRemark()+" ":""))
						)
						.setPositiveButton(activity.getString(R.string.general_got_it), null)
						.show(); 
				return;
			}
			
			// 如果正在进行实时视频聊天则不允许再重复开始视频聊天请求
			if(VideoActivityNew.isChatting() )//|| VideoActivity.isChatting())
			{
				new AlertDialog.Builder(activity)
					.setTitle(activity.getString(R.string.general_prompt))  
					.setMessage(MessageFormat.format(activity.getString(R.string.video_chat_request_at_video_chating)
							, (friendRee != null?friendRee.getNickNameWithRemark()+" ":""))
						)
						.setPositiveButton(activity.getString(R.string.general_got_it), null) 
						.show(); 
				return;
			}

			if(friendRee.isOnline())
			{
				Log.i(TAG, "！接收到的视频请求用户的UID是："+A_UID+",user_id="+friendRee.getUser_uid());
				activity.startActivity(IntentFactory.createVideoCallComeIntent(activity, friendRee.getUser_uid()));
			}
			else
			{
				Log.w(TAG, "！！！！！！！！！接收到的视频请求用户的UID是："+A_UID+"，但他现在不在线，视频聊天取消！");
			}
		}
	}
	
	/**
	 * 【收到实时语音请求处理方式2】当聊天界面没有打开但有其它Activity处于前台时：实时语音聊天请求观察者.（被呼叫方收到后要通知的观察者）
	 * 
	 * 目前本观察者仅用于 {@link MainActivity}中，当此Activity处理前台时即可被通知.
	 */
	public static class RealTimeVoiceChatRequestForNotIntChatUIObserver  extends ObserverMain
	{
		private Activity activity = null;
		
		public RealTimeVoiceChatRequestForNotIntChatUIObserver(Activity activity)
		{
			this.activity = activity;
		}
		
		@Override
		public void updateInMain(Observable observable, Object data)
		{
			final String A_UID = (String)data;
			if(activity != null)
			{
				activity.startActivity(IntentFactory.createChatIntent(activity
						, A_UID, true, System.currentTimeMillis()));
			}
		}
	}
	
	/**
	 * 【收到实时语音请求处理方式1】当聊天界面处于前台时：实时语音聊天请求观察者.（被呼叫方收到后要通知的观察者）
	 * <p>
	 * 为何要使用观察者？理由与类{@link VideoActivityNew.BaseEventForVideoChatObserver}相似。
	 */
	public static class RealTimeVoiceChatRequestObserver extends ObserverMain
	{
		private final static String TAG = RealTimeVoiceChatRequestObserver.class.getSimpleName();
		private Activity activity = null;
		//
		private IRealTimeVoiceWrapper realTimeVoiceWrapper = null;

		private ViewGroup layoutOfRealTimeVoiceOpr = null;
		
		public RealTimeVoiceChatRequestObserver(Activity activity
				, ViewGroup layoutOfRealTimeVoiceOpr, IRealTimeVoiceWrapper realTimeVoiceWrapper)
		{
			this.activity = activity;
			this.layoutOfRealTimeVoiceOpr = layoutOfRealTimeVoiceOpr;
			this.realTimeVoiceWrapper = realTimeVoiceWrapper;
		}

		public void updateInMain(Observable observable, Object data)
		{
			if(activity == null)
				return;
			
			// FIXME：目前当聊天界面正在打开且正在被呼叫中时，点Nitification进来时，
			// 是新建一个ChatActivity，之前的Dialog其实是没被销毁的，所以声音还在，
			// 但VoiceCallComeDialog做单例又不合适，目前就这么的吧，从Notification
			// 点进来会产生各种因异步而导致的边界问题，视频聊天请求就不要这样处理了，
			// 以后问题我的话，干脆实时音频也不要通过Notification点进来了！！！！！
			if(VoiceCallComeDialog.isBeCalling())
			{
				WidgetUtils.showToast(activity, activity.getString(R.string.real_time_chat_be_request_from_notification_duplicate_be_calling)
						, ToastType.WARN);
				return;
			}
			
			// 请求发起人的UID
			final String A_UID = (String)data;
			RosterElementEntity friendRee = 
					MyApplication.getInstance(activity).getIMClientManager().getFriendsListProvider().getFriendInfoByUid(A_UID);
			
			// 如果正在进行实时语音聊天则不允许开始视频聊天请求
			if(realTimeVoiceWrapper != null && realTimeVoiceWrapper.isTalking())
			{
				new AlertDialog.Builder(activity)
					.setTitle(activity.getString(R.string.general_prompt))  
					.setMessage(MessageFormat.format(activity.getString(R.string.real_time_chat_request_at_real_time_voice_chating)
							, (friendRee != null?friendRee.getNickNameWithRemark()+" ":""))
					)
					.setPositiveButton(activity.getString(R.string.general_got_it), null) 
					.show(); 
				return;
			}

			System.out.println(">>>>Integer.parseInt(A_UID)="+Integer.parseInt(A_UID));

			// FIXBUG: NullPointerException (@ObserverProvider$RealTimeVoiceChatRequestObserver:update:214) {main}
			if(friendRee != null && friendRee.isOnline())
			{
				Log.i(TAG, "！接收到的视频请求用户的UID是："+A_UID+",user_id="+friendRee.getUser_uid());
				
				// 不是使用的AnyChat音视频频框架
				new VoiceCallComeDialog(activity, A_UID){
					protected void fireRejectExtra()
					{
						super.fireRejectExtra();
						//	showHint("Lover reject your request");
					}

					protected void fireAcceptPreExtra()
					{
						super.fireAcceptPreExtra();
						//
						realTimeVoiceWrapper.start(false, A_UID, -1);
					}

					protected void fireAcceptExtra()
					{
						super.fireAcceptExtra();
						//
						layoutOfRealTimeVoiceOpr.setVisibility(View.VISIBLE);
					}

					protected void fireAcceptAndSendMesageButErrorExtra()
					{
						super.fireAcceptAndSendMesageButErrorExtra();
						//
						realTimeVoiceWrapper.stopNoConfirm(false);
						//
						layoutOfRealTimeVoiceOpr.setVisibility(View.GONE);
					}
				}.show();
			}
			else
			{
				Log.w(TAG, "！接收到的实时语音聊天请求用户的UID是："+A_UID+"，但他现在不在线，实时语音聊天取消！");
			}
		}
	}
	
	/**
	 * 好友上下线通知观察者(此观察者用于好友元数据中，只要该好友的元数据中的在线状态被设置都会通知观察者).
	 */
	public static class FriendLiveStatusChangeObs extends ObserverMain
	{
		/**
		 * @param data String数组，目前长度=3，第0元素是好友昵称、第1单元是在线状态（0表示下线、1表示上线）、第2单元是好友的uid
		 */
		@Override
		public void updateInMain(Observable observable, Object data)
		{
			if(data != null)
			{
				String[] ii = (String[])data;
				// 上线了
				if((""+RosterElementEntity.LIVE_STATUS_ONLINE).equals(ii[1]))
					fireOnline(ii[0], ii[2]);
				// 下线了
				else if((""+RosterElementEntity.LIVE_STATUS_OFFLINE).equals(ii[1]))
					fireOffline(ii[0], ii[2]);
			}
		}
		
		protected void fireOnline(String nickName, String friendUid)
		{
			//
		}
		
		protected void fireOffline(String nickName, String friendUid)
		{
			//
		}
	}
	
	public static class ReceivedGiftObserverForCommonUI extends ObserverMain
	{
		private Activity activity = null;
		
		public ReceivedGiftObserverForCommonUI(Activity activity)
		{
			this.activity = activity;
		}
		
		@Override
		public void updateInMain(Observable observable, Object data)
		{
			Object[] datas = (Object[])data;
			final String giftIdent = (String)datas[0];
			GiftInPackageMeta gim = (GiftInPackageMeta)datas[1];
			
			// 出于数据加载严谨性考虑，永远要首先确保礼品基础数据必须被首先加载完成才能做其它的哦
			new GiftsProvider.LoadGiftsMetaAsyncTask(activity)
				.setShowProgress(false)
				.execute(
					GiftsProvider.getIntance().getGiftsMeta(false)
					, new Observer()
				{
					@Override
					public void update(Observable observable, Object data)
					{
						//** 把数据刷新到UI上
						Gift g = ((GiftsMeta)data).getGift(giftIdent);
						
						if(g != null)
							WidgetUtils.showToast(activity
								, MessageFormat.format(activity.getString(R.string.chatting_gift_received_hint)
										, g.getGift_name(), g.getPrice())
								, ToastType.OK);
						
					}
				});
		}
	}
}

